package cn.itsource.pethome.base.service.impl;

import cn.itsource.pethome.base.constant.PetHomeConstant;
import cn.itsource.pethome.base.service.IVerificationCodeService;
import cn.itsource.pethome.base.util.SendMsgUtil;
import cn.itsource.pethome.base.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class VerificationCodeServiceImpl implements IVerificationCodeService{

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendRegisterMobileCode(String phone) {
        //获取随机的四位验证码
        String code = StrUtils.getComplexRandomString(4);

        //通过手机号码在redisTemplate中获取对应的验证码
        String codeValue = (String) redisTemplate.opsForValue().get(PetHomeConstant.REGISTER_VERIFICATION_CODE + ":" + phone);
        if(!StringUtils.isEmpty(codeValue)){
            //获取第一次的毫秒时间
            Long beginTimer = Long.valueOf(codeValue.split(":")[1]);
            //验证码有效时间是5分钟，如果在1分钟内发送第二次则提示一分钟内不能重复发送
            if(System.currentTimeMillis() - beginTimer < 60000){
                throw new RuntimeException("60秒内不能重复发送验证码");
            }
            //如果没有走抛异常就证明验证码超过了1分钟但不到5分钟，则再发送一次同样的验证码
            code = codeValue.split(":")[0];
        }

        //把验证码存储到redisTemplate对象中，有效时间设置为5分钟
        redisTemplate.opsForValue().set(PetHomeConstant.REGISTER_VERIFICATION_CODE + ":" + phone, code + ":" + System.currentTimeMillis());
        String content = "尊敬的用户，你的验证码为:"+code+",请在5分钟以内完成验证";

        SendMsgUtil.sendMsg(phone, content);

    }

    public static void main(String[] args) {
        String str = "ysd";
        System.out.println(StringUtils.isEmpty(str));
    }
}
